"""
教师仪表盘视图
"""
from datetime import datetime, timedelta
from django.db.models import Count, Q
from django.utils import timezone
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from students.models import Student
from resume_management.models import Resume
from interviews.models import Interview
from jobs.models import Job, JobApplication


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def my_students_statistics(request):
    """获取教师负责学生的统计数据"""
    try:
        user = request.user
        
        if user.role != 'teacher':
            return Response(
                {'error': '此接口仅供教师使用'}, 
                status=status.HTTP_403_FORBIDDEN
            )
        
        # 获取该教师负责的学生
        my_students = Student.objects.filter(advisor=user)
        
        if not my_students.exists():
            return Response({
                'total_students': 0,
                'employment_stats': {
                    'employed': 0,
                    'unemployed': 0,
                    'further_study': 0,
                    'self_employed': 0,
                    'military': 0
                },
                'resume_stats': {
                    'total': 0,
                    'pending_review': 0,
                    'approved': 0,
                    'needs_revision': 0
                },
                'interview_stats': {
                    'total': 0,
                    'this_month': 0,
                    'completed': 0
                },
                'employment_rate': 0.0
            })
        
        # 统计学生就业状态
        employment_stats = my_students.aggregate(
            employed=Count('id', filter=Q(employment_status='employed')),
            unemployed=Count('id', filter=Q(employment_status='unemployed')),
            further_study=Count('id', filter=Q(employment_status='further_study')),
            self_employed=Count('id', filter=Q(employment_status='self_employed')),
            military=Count('id', filter=Q(employment_status='military'))
        )
        
        # 统计简历状态
        resume_stats = Resume.objects.filter(student__in=my_students).aggregate(
            total=Count('id'),
            pending_review=Count('id', filter=Q(status='pending_review')),
            approved=Count('id', filter=Q(status='approved')),
            needs_revision=Count('id', filter=Q(status='needs_revision'))
        )
        
        # 统计面试情况
        current_month = timezone.now().month
        interview_stats = Interview.objects.filter(student__in=my_students).aggregate(
            total=Count('id'),
            this_month=Count('id', filter=Q(created_at__month=current_month)),
            completed=Count('id', filter=Q(status='completed'))
        )
        
        # 计算就业率
        total_students = my_students.count()
        employed_students = employment_stats['employed'] + employment_stats['self_employed']
        employment_rate = round((employed_students / total_students) * 100, 2) if total_students > 0 else 0.0
        
        data = {
            'total_students': total_students,
            'employment_stats': employment_stats,
            'resume_stats': resume_stats,
            'interview_stats': interview_stats,
            'employment_rate': employment_rate
        }
        
        return Response(data)
        
    except Exception as e:
        return Response(
            {'error': f'获取学生统计失败: {str(e)}'}, 
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def pending_reviews(request):
    """获取待审核的简历"""
    try:
        user = request.user
        
        if user.role != 'teacher':
            return Response(
                {'error': '此接口仅供教师使用'}, 
                status=status.HTTP_403_FORBIDDEN
            )
        
        # 获取该教师负责学生的待审核简历
        my_students = Student.objects.filter(advisor=user)
        pending_resumes = Resume.objects.filter(
            student__in=my_students,
            status='pending_review'
        ).order_by('-updated_at')
        
        resume_data = []
        for resume in pending_resumes:
            resume_data.append({
                'id': resume.id,
                'title': resume.title,
                'student_name': resume.student.name,
                'student_id': resume.student.student_id,
                'completion_rate': float(resume.completion_rate),
                'submitted_at': resume.updated_at,
                'resume_type': resume.resume_type,
                'current_step': resume.current_step
            })
        
        data = {
            'pending_resumes': resume_data,
            'total_count': len(resume_data),
            'urgent_count': len([r for r in resume_data if 
                               (timezone.now() - r['submitted_at']).days > 3])
        }
        
        return Response(data)
        
    except Exception as e:
        return Response(
            {'error': f'获取待审核简历失败: {str(e)}'}, 
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def monthly_schedule(request):
    """获取本月面试安排"""
    try:
        user = request.user
        
        if user.role != 'teacher':
            return Response(
                {'error': '此接口仅供教师使用'}, 
                status=status.HTTP_403_FORBIDDEN
            )
        
        # 获取该教师负责学生的本月面试
        my_students = Student.objects.filter(advisor=user)
        current_month = timezone.now().month
        current_year = timezone.now().year
        
        monthly_interviews = Interview.objects.filter(
            student__in=my_students,
            scheduled_time__month=current_month,
            scheduled_time__year=current_year
        ).order_by('scheduled_time')
        
        interview_data = []
        for interview in monthly_interviews:
            interview_data.append({
                'id': interview.id,
                'student_name': interview.student.name,
                'student_id': interview.student.student_id,
                'title': interview.title,
                'interview_type': interview.interview_type,
                'scheduled_time': interview.scheduled_time,
                'status': interview.status,
                'location': interview.location,
                'feedback': interview.feedback
            })
        
        # 按日期分组
        schedule_by_date = {}
        for interview in interview_data:
            date_str = interview['scheduled_time'].strftime('%Y-%m-%d')
            if date_str not in schedule_by_date:
                schedule_by_date[date_str] = []
            schedule_by_date[date_str].append(interview)
        
        # 统计本月面试状态
        stats = {
            'total': len(interview_data),
            'scheduled': len([i for i in interview_data if i['status'] == 'scheduled']),
            'completed': len([i for i in interview_data if i['status'] == 'completed']),
            'cancelled': len([i for i in interview_data if i['status'] == 'cancelled'])
        }
        
        data = {
            'monthly_interviews': interview_data,
            'schedule_by_date': schedule_by_date,
            'statistics': stats,
            'month': f'{current_year}-{current_month:02d}'
        }
        
        return Response(data)
        
    except Exception as e:
        return Response(
            {'error': f'获取月度面试安排失败: {str(e)}'}, 
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def employment_progress(request):
    """获取学生就业进展"""
    try:
        user = request.user
        
        if user.role != 'teacher':
            return Response(
                {'error': '此接口仅供教师使用'}, 
                status=status.HTTP_403_FORBIDDEN
            )
        
        # 获取该教师负责的学生
        my_students = Student.objects.filter(advisor=user)
        
        student_progress = []
        for student in my_students:
            # 获取学生的就业相关数据
            resume_count = Resume.objects.filter(student=student).count()
            application_count = JobApplication.objects.filter(student=student).count()
            interview_count = Interview.objects.filter(student=student).count()
            
            # 获取最新简历状态
            latest_resume = Resume.objects.filter(student=student).first()
            resume_status = latest_resume.status if latest_resume else 'no_resume'
            
            # 获取最近的申请状态
            recent_applications = JobApplication.objects.filter(student=student).order_by('-created_at')[:3]
            
            # 计算就业进展分数
            progress_score = calculate_employment_progress_score(
                student, resume_count, application_count, interview_count
            )
            
            student_progress.append({
                'student_id': student.id,
                'student_name': student.name,
                'student_number': student.student_id,
                'employment_status': student.employment_status,
                'resume_count': resume_count,
                'application_count': application_count,
                'interview_count': interview_count,
                'resume_status': resume_status,
                'recent_applications': [
                    {
                        'job_title': app.job.title if app.job else '未知岗位',
                        'status': app.status,
                        'applied_date': app.created_at
                    } for app in recent_applications
                ],
                'progress_score': progress_score,
                'last_activity': get_last_activity_date(student)
            })
        
        # 按进展分数排序
        student_progress.sort(key=lambda x: x['progress_score'], reverse=True)
        
        # 统计总体情况
        total_students = len(student_progress)
        high_progress = len([s for s in student_progress if s['progress_score'] >= 70])
        medium_progress = len([s for s in student_progress if 40 <= s['progress_score'] < 70])
        low_progress = len([s for s in student_progress if s['progress_score'] < 40])
        
        data = {
            'student_progress': student_progress,
            'summary': {
                'total_students': total_students,
                'high_progress': high_progress,
                'medium_progress': medium_progress,
                'low_progress': low_progress,
                'employment_rate': round(
                    len([s for s in student_progress if s['employment_status'] in ['employed', 'self_employed']]) 
                    / total_students * 100, 2
                ) if total_students > 0 else 0
            }
        }
        
        return Response(data)
        
    except Exception as e:
        return Response(
            {'error': f'获取就业进展失败: {str(e)}'}, 
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


# 辅助函数
def calculate_employment_progress_score(student, resume_count, application_count, interview_count):
    """计算就业进展分数"""
    score = 0
    
    # 基础分数：有简历
    if resume_count > 0:
        score += 20
    
    # 简历质量分数
    latest_resume = Resume.objects.filter(student=student).first()
    if latest_resume:
        if latest_resume.status == 'approved':
            score += 25
        elif latest_resume.status in ['pending_review', 'under_review']:
            score += 15
        elif latest_resume.completion_rate >= 80:
            score += 10
    
    # 申请活跃度分数
    if application_count >= 5:
        score += 20
    elif application_count >= 3:
        score += 15
    elif application_count >= 1:
        score += 10
    
    # 面试机会分数
    if interview_count >= 3:
        score += 20
    elif interview_count >= 1:
        score += 15
    
    # 就业状态分数
    if student.employment_status == 'employed':
        score += 15
    elif student.employment_status == 'self_employed':
        score += 15
    elif student.employment_status == 'further_study':
        score += 10
    
    return min(score, 100)


def get_last_activity_date(student):
    """获取学生最后活动时间"""
    from django.db.models import Max
    
    # 获取各种活动的最新时间
    resume_date = Resume.objects.filter(student=student).aggregate(
        last_date=Max('updated_at')
    )['last_date']
    
    application_date = JobApplication.objects.filter(student=student).aggregate(
        last_date=Max('applied_at')
    )['last_date']
    
    interview_date = Interview.objects.filter(student=student).aggregate(
        last_date=Max('created_at')
    )['last_date']
    
    # 找出最新的活动时间
    dates = [d for d in [resume_date, application_date, interview_date] if d is not None]
    
    if dates:
        return max(dates)
    else:
        return student.created_at
